﻿using B.S.DataBasic.Domain.RBAC;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B.S.DataBasic.Infrastructure.Medi
{
    public class LoginMediator
    {
        private readonly DataDbContext _context;
        public LoginMediator(DataDbContext context)
        {
            _context = context;
        }
        public bool Login(string username, string password)
        {
            var hashedPassword = GetMd5Hash(password);
            var user = _context.Users.FirstOrDefault(u => u.Username == username && u.Password == hashedPassword);
            return user != null;
        }
        public User GetUserByUsername(string username)
        {
            return _context.Users
                .Include(u => u.Role)
                .ThenInclude(r => r.Permissions)
                .FirstOrDefault(u => u.Username == username);
        }
        private string GetMd5Hash(string input)
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            byte[] hashBytes = ComputeMd5Hash(inputBytes);
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sBuilder.Append(hashBytes[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }
        private byte[] ComputeMd5Hash(byte[] inputBytes)
        {
            if (inputBytes.Length == 0)
            {
                // 这里没有返回值
            }
            // 其他计算逻辑
            byte[] hashBytes = new byte[16]; // 假设这里是计算结果
            return hashBytes;
        }
        private uint LeftRotate(uint x, uint c)
        {
            return (x << (int)c) | (x >> (32 - (int)c));
        }

        public IQueryable<User> GetAllUsers()
        {
            return _context.Users
                .Include(u => u.Role)
                .ThenInclude(r => r.Permissions);
        }
    }
}
